<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import utils from '../utils/utils'
import request from '../utils/request'
import { login } from '../api/login'
import router from '../router'

const loading = ref(false)

const ruleFormRef = ref<FormInstance>()
// 在script部分添加
const captchaUrl = ref('')
// 获取验证码
const refreshCaptcha = async () => {
  await request.get('/captchaImage').then(res => {
    captchaUrl.value = `data:image/jpeg;base64,${res.data.img}`
    ruleForm.uuid = res.data.uuid
  })
}

const ruleForm = reactive({
  username: 'admin',
  password: '5216917',
  verificationCode: '',
  uuid: '',
})

const rules = reactive<FormRules<typeof ruleForm>>({
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },

  ],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      loading.value = true // 开始加载
      login(ruleForm.username, ruleForm.password, ruleForm.verificationCode, ruleForm.uuid).then((res) => {
        if (res.data.code == 200) {
          // 登录成功处理
          utils.showMessage(res.data.message, 'success', 2000);
          console.log(res.data);
          //存储jwt令牌到本地存储中
          localStorage.setItem('token', res.data.data)
          //跳转到主页面
          router.push('/home')
        }
        else {
          utils.showMessage(res.data.message, 'error', 2000);
          // 如果是验证码错误，自动刷新验证码
          if (res.data.message.includes('验证码错误') || res.data.message.includes('账号后置密码错误')) {
            refreshCaptcha();
            ruleForm.verificationCode = ''; // 清空输入框
          }
        }
      })
        .catch((error) => {
          console.log(error);
        }).finally(() => {
          loading.value = false // 结束加载
        })
    } else {
      utils.showMessage('请输入信息', 'error', 2000)
    }
  })
}
// 初始化时获取
onMounted(() => {
  refreshCaptcha()
})
</script>

<template>
  <!-- 外层全屏容器 -->
  <div class="login-container">
    <el-card class="login-card">
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules"
        class="demo-ruleForm">
        <h3 class="title">博物馆后台管理系统</h3>
        <el-form-item prop="username">
          <el-input placeholder="账号" v-model.number="ruleForm.username" type="text" class="input">
            <template #prefix>
              <el-icon>
                <UserFilled />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password" class="input">
          <el-input placeholder="密码" v-model="ruleForm.password" type="password" autocomplete="off" class="input">
            <template #prefix>
              <el-icon>
                <Lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="verificationCode" class="captcha-container">
          <div class="captcha-wrapper">
            <!-- 输入框 -->
            <el-input v-model="ruleForm.verificationCode" type="text" placeholder="验证码" class="captcha-input">
              <template #prefix>
                <el-icon>
                  <Bell />
                </el-icon>
              </template>
            </el-input>
            <!-- 验证码图片 -->
            <div class="captcha-image" @click="refreshCaptcha">
              <img :src="captchaUrl" width="100px" alt="验证码" class="captcha-img" />
              <span class="refresh-text">点击刷新</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button :loading="loading" placeholder="验证码" class="submit" type="primary"
            @click="submitForm(ruleFormRef)">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
/* 关键样式 */
.login-container {
  min-height: 100vh;
  /* 占据全屏高度 */
  display: flex;
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中 */
  background: #f0f2f5;
  /* 推荐背景色 */
}

.login-card {
  width: 400px;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.title {
  margin: 0 auto 30px auto;
  text-align: center;
  color: #707070;
}

.submit {
  width: 80%;
  margin: 0 auto;
}

.input {
  height: 38px;
}

/* 容器样式 */
.captcha-container {
  margin-bottom: 22px;
}

/* 输入框和图片容器 */
.captcha-wrapper {
  display: flex;
  align-items: center;
  /* 垂直居中 */
  gap: 10px;
  /* 元素间距 */
}

/* 输入框样式 */
.captcha-input {
  height: 38px;
  flex: 1;
  /* 自动填充剩余空间 */
  width: 250px;
}

/* 验证码图片容器 */
.captcha-image {
  position: relative;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  width: 100px;
}

/* 验证码图片 */
.captcha-img {
  display: block;
  height: 38px;
  /* 与输入框高度一致 */
  width: auto;
  margin: 0 auto;
}

/* 刷新文字 */
.refresh-text {
  position: absolute;
  width: 100%;
  text-align: center;
  color: orange;
  font-size: 12px;
  line-height: 18px;
  font-weight: 900;
  opacity: 0;
  transition: opacity 0.3s;
  left: 0;
  top: 25%;
}

.captcha-image:hover .refresh-text {
  opacity: 1;
}

/* 手机端适配样式 */
@media (max-width: 768px) {
  .login-card {
    width: 90%;
    /* 在小屏幕上宽度调整为90% */
    padding: 15px;
    /* 调整内边距 */
  }

  /* 如果需要，可以进一步调整其他元素的样式 */
  .captcha-wrapper {
    display: flex;
   
    /* 在小屏幕上验证码输入框和图片垂直排列 */
    gap: 5px;
    /* 调整垂直间距 */
  }

  .captcha-input {
    width: 70%;
    /* 输入框宽度占满容器 */
  }

  .captcha-image {
    width: 30%;
    /* 图片容器宽度占满容器 */
    height: auto;
    /* 高度自适应 */
  }

  .captcha-img {
    width: 100%;
    /* 图片宽度自适应 */
    height: 38px;
    /* 保持图片高度与输入框一致 */
  }

  .submit {
    width: 100%;
    /* 按钮宽度占满容器 */
  }
}
</style>
